// pages/post/post_content/post_content.js
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
let util = require('../../../utils/content_check.js')
const { formatTime } = require('../../../utils/util.js')
const app = getApp()
Page({

  data: {
    postId: null,
    title: null,
    content: null,
    avatar: null,
    authorName: null,
    authorId: null,
    createTime: null,
    viewNumber: null,
    canEdit: false,
    comments:[],
    inputPlaceHolder:'快来发表评论吧 ~ ',
  },

  // 点击编辑帖子按钮
  editPost: function (e){
    wx.navigateTo({
      url: '../createPost/createPost?id=' + this.data.postId,
    })
  },
  // 点击删除帖子按钮
  deletePost: function (e){
    var id = this.data.postId
    wx.showModal({
      title: '提示',
      content: '确认删除该论坛帖?',
      cancelText:'取消',
      success: function (res) {
        if (res.confirm) {
          app.sendDeleteRequest('/community/cpc/post/'+id, (res) => {
            if(res.code == 200){
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              wx.navigateTo({
                url: '../cpc'
              })
            }else{
              wx.showToast({
                title: '删除失败，请稍后再试！',
                icon: 'none',
                duration: 2000
              })
            }
          }, (err) => {
            console.log(err.errMsg)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 拉取帖子内容
  getPost(id){
    app.sendGetRequest('/community/cpc/post/'+id, (res) => {
      // console.log('帖子', res)
      var data = res.data
      this.setData({
        title: data.title,
        content: data.content,
        authorName: data.authorName,
        authorId: data.authorId,
        createTime: data.postCreateTime,
        viewNumber: data.viewNumber
      })
      // 获取当前登录用户的id,判断与作者id是否一致，决定了是否显示编辑按钮
      var loginUser = app.getUserInfo()
      if(loginUser){
        this.setData({
          avatar: loginUser.avatar,
          canEdit: loginUser.userId==this.data.authorId
        })
      }else{
        this.setData({
          avatar: "https://s4.ax1x.com/2021/12/23/T8kUoR.jpg",
          canEdit: false
        })
      }
    }, (err) => {
      console.log(err.errMsg)
    })
  },

  // 工具函数，判断元素是否在列表中
  inList: function (item, list){
    var result = false
    for(var i=0; i<list.length; i++){
      if(item==list[i]){
        result = true
        break
      }
    }
    return result
  },
  // 把评论整理成正确的显示顺序
  getCommentsSorted: function (list){
    // index从小到大 等同于 时间先后，不需要再排序了
    // 首先选出不是回复某人的单独评论，按时间从先到后排序，再把回复某条的评论插到对应评论组里

    // [[0,1], [2], [3]]只存储评论的index
    var comment_group_list = []
    // 存储回复类评论的整个评论信息
    var comment_to_reply_list = []

    for(var i=0; i<list.length; i++){
      if(list[i].parentCommentId==null){
        comment_group_list.push([list[i].commentId])
      }else{
        comment_to_reply_list.push(list[i])
      }
    }
    for(var i=0; i<comment_to_reply_list.length; i++){
      for(var j=0; j<comment_group_list.length; j++){
        if(this.inList(comment_to_reply_list[i].parentCommentId, comment_group_list[j])){
          comment_group_list[j].push(comment_to_reply_list[i].commentId)
          break;
        }
      }
    }
    var sorted_comment_index_list = [].concat.apply([], comment_group_list)
    var result = []
    for(var i=0; i<sorted_comment_index_list.length; i++){
      for(var j=0; j<list.length; j++){
        if(list[j].commentId == sorted_comment_index_list[i]){
          result.push(list[j])
        }
      }
    }
    return result
  },

  // 拉取所有评论
  getComment(id){
    app.sendGetRequest('/community/cpc/post/comment/'+id, (res) => {
      var data = res.data
      // console.log('评论', data)
      var comments = this.getCommentsSorted(data)
      this.setData({
        comments: comments
      })
      // console.log('整理好的评论', comments)
    }, (err) => {
      console.log(err.errMsg)
    })
  },

  // 判断由哪个页面跳转而来，从而决定返回哪个页面
  onLoad: function (options) {
    this.setData({
      postId: options.id
    })
    this.getPost(this.data.postId)
    this.getComment(this.data.postId)
  },
  
  // 评论输入框接收输入
  onInputComment: function (e) {
    var comment = e.detail.value;
    this.setData({
      newCommentContent: comment
    })
  },
  // 点击评论，表明即将输入的评论为回复
  onCommentTap: function (e) {
    var id = e.currentTarget.dataset.comment_id
    var userName = e.currentTarget.dataset.user_name
    this.setData({
      newCommentParentCommentId: id,
      inputPlaceHolder: "回复 " + userName + " :",
    })
  },
  // 清除点击评论的回复效果
  cancelReply: function(e) {
    this.setData({
      newCommentParentCommentId: null,
      inputPlaceHolder: '快来发表评论吧 ~ ',
    })
  },
  resetNewComment:function(){
    this.setData({
      newCommentParentCommentId :null,
      newCommentContent :null,
      NCcommentedid :null,
      syncTime :null,
      inputPlaceHolder:'快来发表评论吧 ~ '
    })
  },
  // 点击评论发送
  onSendTap: function(e){
    var time = formatTime(new Date())
    var newComment = {
      parentCommentId: this.data.newCommentParentCommentId,
      content: this.data.newCommentContent,
      postId: this.data.postId,
      syncTime: time,
      deleteFlag: 0
    }
    app.sendPostRequest('/community/cpc/post/comment', newComment, (res) => {
      console.log('评论结果', res)
      if(res.code==200){
        wx.showToast({
          title: '评论成功！',
          icon: 'none',
          duration: 2000
        })
        this.getComment(this.data.postId)
        this.resetNewComment()
      }else{
        wx.showToast({
          title: '评论失败，请稍后再试！',
          icon: 'none',
          duration: 2000
        })
      }
    }, (err) => {
      console.log(err.errMsg)
    })
  },
})